package Code;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JTextArea;
import javax.swing.table.DefaultTableModel;
import DatabaseCommands.DatabaseInfo;
import Panels.DatabaseHome;


public class TablePanelInfo{

	private DatabaseInfo DInfo=DatabaseInfo.getInstance();
	private DatabaseHome DBHome=DatabaseHome.getInstance();
	private String QueryLocation;
	private List<String> Queries=new ArrayList<String>();
	private List<String> QueryErrors=new ArrayList<String>();
	private JTextArea QueryTextArea;
	private DefaultTableModel TModel;
	public String TableName=null; 
	
	
	public TablePanelInfo(String Location){
		QueryLocation=Location;
	}
	
	
	public void SetResultsTable(DefaultTableModel Model){
		TModel=Model;
	}
	
	
	public void SetTextArea(JTextArea QueryText){
		QueryTextArea=QueryText;
	}
	
	
	public JTextArea GetTextArea(){
		return QueryTextArea;
	}
	
	
	public String GetQueryLocation(){
		return QueryLocation;
	}
	
	
	public void GetQueries(){
		Queries=new ArrayList<String>(Arrays.asList(QueryTextArea.getText().split("\\n")));
	}

	
	public void RemoveTableRows(){
		int RowCount=(TModel.getRowCount()-1);
		for(int x=RowCount;x>=0;x--){
			TModel.removeRow(x);
		}
	}
	
	
	public void RunQuery(){
		GetQueries();
		
		RemoveTableRows();
		String[] Row=new String[3];
		
		for(String Item:Queries){
			if(Item.trim().length()==0){continue;}
			try{
				Row[1]=Item;
				DInfo.GetConnection().createStatement().execute(Item);
			}catch(Exception Event){
				Row[2]=Event.getMessage();
				QueryErrors.add(Event.getMessage());
			}
			Row[0]=(Row[2]==null?"Good":"Bad");
			TModel.addRow(Row);
			Row[0]=null;
			Row[1]=null;
			Row[2]=null;
		}
		
		DBHome.UpdateTableTreeView();
	}
	
	
}
